import React, { useState } from 'react';
import { Modal, Spin, Button } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import QRCode from 'qrcode.react';
import styles from './index.less';
interface PorpsType {
  login_code_url: any;
  gzh_open_id: any;
  id: any;
}
const PreView: React.FC<PorpsType> = (porps) => {
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [url, setUrl] = useState<string>('');
  const dataURLtoBlob = (dataurl: any) => {
    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  };
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const downloadFile = (url: string, name: string) => {
    const a = document.createElement('a');
    a.setAttribute('href', url);
    a.setAttribute('download', name);
    a.setAttribute('target', '_blank');
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };
  const handleDownLoadQRCode = () => {
    const Qr: any = document.getElementById('qrCode');
    if (Qr) {
      const canvasUrl = Qr.toDataURL('image/png');
      const myBlob = dataURLtoBlob(canvasUrl);
      const myUrl = URL.createObjectURL(myBlob);
      downloadFile(myUrl, porps.id);
    }
  };
  const viewContent = () => {
    return (
      <Spin spinning={isModalVisible && url ? false : true}>
        {isModalVisible && url ? (
          <div className={styles.show_info}>
            <div className={styles.operation}>
              <QRCode
                id={'qrCode'}
                value={url}
                size={300} //二维码的宽高尺寸
                fgColor="#000000" //二维码的颜色
              />
              <Button
                type="primary"
                icon={<DownloadOutlined />}
                className={styles.operationBtn}
                onClick={handleDownLoadQRCode}
              >
                下载二维码
              </Button>
            </div>
          </div>
        ) : (
          <></>
        )}
      </Spin>
    );
  };
  return (
    <>
      <Button
        type="primary"
        shape="round"
        size="small"
        danger={porps.gzh_open_id ? false : true}
        onClick={async () => {
          await setUrl(porps.login_code_url);
          await setIsModalVisible(true);
        }}
      >
        {porps.gzh_open_id ? '已授权' : '未授权'}
      </Button>
      <Modal
        title={'授权'}
        visible={isModalVisible}
        width={500}
        footer={null}
        onCancel={() => {
          setIsModalVisible(false);
        }}
      >
        {isModalVisible && viewContent()}
      </Modal>
    </>
  );
};
export default PreView;
